package cn.pet.service.manage.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

@Component
public class JWTUtil {
    @Value("${pet.auth.jwt.expire}")
    private Long expireTime;

    @Value("${pet.auth.jwt.secret}")
    private String secret;

    public String createToken(Serializable userId){
        String token = JWT.create()
                .withSubject(userId.toString())
                .withExpiresAt(Instant.ofEpochMilli(ZonedDateTime.now(ZoneId.systemDefault())
                        .toInstant().toEpochMilli() + expireTime))
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    public String createToken(Serializable userId, List<Integer> roleIds){
//        roleIds.add(1);
        String token = JWT.create()
                .withSubject(userId.toString())
                .withExpiresAt(Instant.ofEpochMilli(ZonedDateTime.now(ZoneId.systemDefault())
                        .toInstant().toEpochMilli() + expireTime))
                // token中添加对应的角色
                .withClaim("roles",roleIds)
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    public boolean isTokenExpired(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        jwtVerifier.verify(token);

        final Date date = JWT.decode(token).getExpiresAt();
        return date.before(new Date());
    }

    public String getUserId(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        jwtVerifier.verify(token);

        String userId = JWT.decode(token).getSubject();
        return userId;
    }

}
